<?php
class BackupsController extends CmsAppController
{
	var $name = 'Backups';
	var $uses = array();


	function admin_export()
	{
		//Configure::write('debug',0);
		App::import('Model','AppModel');
		$modelObj = new AppModel(null,false);
		$tables = $modelObj->query('Show table status');
		$sql = '';
		foreach($tables as $table)
		{
			$tableName = $table['TABLES']['Name'];
			$tableSchema =  $modelObj->query('DESCRIBE '.$tableName);
			$tableCloumn = Set::combine($tableSchema,'{n}.COLUMNS.Field','{n}.COLUMNS.Field');
			
			$sql .= "####### Creating Table $tableName #######\n\n";
			$sql .= " DROP TABLE IF EXISTS `$tableName` ;\n\n\n\n\n";
			$createQuery = $modelObj->query("Show Create table $tableName");
			$sql .=  $createQuery[0][0]['Create Table'].";\n\n";
			$sql .=  $this->__insertDataQuery($tableName,$modelObj);
			$sql .= "\n\n";
			
		}
		file_put_contents(WWW_ROOT.'backup.sql',$sql);
		header("Content-type: text/html");
		header("Content-Disposition: attachment; filename=backup.sql");
		readfile(WWW_ROOT.'backup.sql');
		exit;
	}

	function __insertDataQuery($table,&$modelObj)
	{
		$sql = '#########  Dumping data Into '.$table."#########\n";
		$data  = $modelObj->query('Select * from '.$table.' where 1=1;');
		foreach($data as $row)
		{
			$columnsName  = array_keys($row[$table]);
			foreach($row[$table] as $column => $value )
			{
				if(!is_numeric($value))
				{
					$value = mysql_real_escape_string($value);
					//$value = str_replace("\r", '', $value);
					//$value = str_replace("\n", "\\n", $value);
					$row[$table][$column]  = '\''.$value.'\'';
				}
			}
			//prd($row);
			$sql  .= ' INSERT INTO `'.$table.'` ('.implode(',',$columnsName).')   VALUES ('.implode(',',$row[$table]).");\n";
		}
		return $sql;
	}
}

?>